package com.sos.controller;

import com.sos.model.entity.User;
import com.sos.model.vo.ResultVO;
import com.sos.service.FileUploadService;
import com.sos.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/files")
@RequiredArgsConstructor
@Tag(name = "文件上传", description = "文件上传相关接口")
@SecurityRequirement(name = "bearerAuth")
@Slf4j
public class FileUploadController {

    private final FileUploadService fileUploadService;
    private final UserService userService;

    @PostMapping("/upload-avatar")
    @Operation(summary = "上传用户头像", description = "上传用户头像文件，返回文件访问URL")
    @Transactional
    public ResultVO<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        log.info("开始处理用户头像上传请求，文件名: {}", file.getOriginalFilename());
        try {
            ResultVO<String> result = fileUploadService.uploadAvatar(file);
            
            // 更新用户头像URL
            if (result.getCode() == 200) {
                User currentUser = userService.getCurrentUser();
                currentUser.setAvatar(result.getData());
                // 这里不需要显式保存，因为UserService.getCurrentUser()返回的是托管实体
            }
            
            log.info("用户头像上传完成，结果: {}", result);
            return result;
        } catch (Exception e) {
            log.error("用户头像上传失败", e);
            throw e;
        }
    }
    
    @GetMapping("/test")
    public String test() {
        log.info("测试接口被调用");
        return "test success";
    }
}